
const express = require('express')
const {buildSchema}=require("graphql")
const {graphqlHTTP} = require('express-graphql')
const app = express()
const port=3000
//-----------------------------------------链接数据库
let mongoose=require("mongoose")
mongoose.connect("mongodb://localhost:27017/admin") //指定对应名称
//-----------------------------------------


// 限制film集合只能有三个字段
var FilmModel=mongoose.model('film',new mongoose.Schema({
    name:String,
    price:Number,
    poster:String
}))
//创建模型
// FilmModel.create
// FilmModel.find
// FilmModel.update
// FilmModel.delete



//创建一个sccama
//冒号后面定义返回类型
let Schema=buildSchema(`
    type Query{
        getFilmList:[Film]  
    }

    type Mutation{
        createFilm(input:FilmInput):Film,
        updateFilm(id:String!,input:FilmInput):Film
        deleteFilm(id:String!):Int
    }
    
    type Film{
        id:String,
        name:String,
        price:Int,
        poster:String
    }

    input FilmInput{
        name:String,
        price:Int,
        poster:String
    }
`)   

// 请求操作
const root={
    createFilm({input}){
        return FilmModel.create({
            ...input
        })
    },

    getFilmList(){
        return  FilmModel.find()
    },

    updateFilm({id,input}){
        return FilmModel.updateOne({
            _id:id
        },{
            ...input
        }).then(res=>FilmModel.find({_id:id})).then(res=>res[0])
    },

    deleteFilm({id}){
        return FilmModel.deleteOne({_id:id}).then(res=>1)
    }
}

app.use('/graphql',graphqlHTTP({
    schema:Schema,
    rootValue:root,
    graphiql:true //开启调试器
}))

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})